<template>
  <div style="height:100%">
    <t-dialog
      title="机构选择"
      :closeBtn="true"
      attach="body"
      :visible.sync="visible"
      :showOverlay="true"
      @opened="handleOpen"
      width="20%"
      @closed="$emit('closed')"
    >
      <t-input placeholder="输入关键字进行过滤" v-model="filterText" />
      <div class="block" />
      <div style="height: 40vh; overflow-y: scroll">
        <el-tree
          ref="tree"
          :data="treeData"
          :accordion="true"
          node-key="id"
          :filter-node-method="filterNode"
          :default-expanded-keys="defaultExpandedKeys"
          :show-checkbox="propMultiSelect"
          highlight-current
        >
          <span slot-scope="{node, data}">
            <span @dblclick="confirm">{{data.label}}</span>
          </span>
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">
          <i class="fa fa-close"></i> 取消
        </el-button>
        <el-button size="mini" @click="clear" v-if="propAllowClear">
          <i class="fa fa-eraser"></i> 清除
        </el-button>
        <el-button size="mini" @click="refresh">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
        <el-button size="mini" type="primary" @click="confirm">
          <i class="fa fa-check"></i> 确定
        </el-button>
      </div>
    </t-dialog>
  </div>
</template>

<script>
export default {
  name: 'OfficeTreeSelect',
  props: {
    propVisible: Boolean, // 是否可见
    propAllowClear: Boolean, // 是否允许清空
    propMultiSelect: Boolean, // 是否允许多选
    // propAppedToBody: Boolean, // 挡在嵌套dialog中，此属性的值需要为true，否则显示会出现问题
  },
  data() {
    return {
      visible: this.propVisible,
      filterText: '',
      treeData: [],
      treeEntry: '/office/all',
      defaultProps: {
        children: 'children',
        label: 'label',
      },
    }
  },
  computed: {
    defaultExpandedKeys() {
      return this.treeData.length > 0 ? this.treeData.map((o) => o.id) : ['0']
    },
  },
  methods: {
    handleOpen() {
      this.fetchTreeData()
    },
    fetchTreeData() {
      this.$ajax.get(this.treeEntry, {}).then((response) => {
        if (!response.success) {
          this.$error(response.msg)
        }
        const rootNode = {
          id: '0',
          name: '根节点',
          parentId: 'none',
        }
        this.treeData = global.utils.convertToTree(response.data, {
          rootNode,
          keyFieldName: 'id',
          parentFieldName: 'parentId',
          labelFieldName: 'name',
        })
        /* this.treeData = global.utils.convertToTree(response.data, {
          keyFieldName: 'id',
          parentFieldName: 'parentId',
          labelFieldName: 'name'
        }) */

        // 设置默认展开
        if (this.treeData.length >= 1) {
          this.$refs.tree.store
            ._getAllNodes()
            .filter((o) => o.data.id == this.treeData[0].id)
            .forEach((o) => (o.expanded = true))
        }
      })
    },
    filterNode(val, data) {
      if (!val) return true
      return data.label.toLowerCase().indexOf(val.toLowerCase()) !== -1
    },
    clear() {
      this.visible = false
      this.$emit('clear')
    },
    refresh() {
      this.fetchTreeData()
    },
    confirm() {
      let selectedNodes = null

      if (this.propMultiSelect) {
        selectedNodes = this.$refs.tree.getCheckedNodes()
      } else {
        let currentNode = this.$refs.tree.getCurrentNode()
        if (currentNode.id == 0) {
          this.utilMessage.warning('请选择非跟节点机构')
          return
        }
        if (currentNode) {
          selectedNodes = new Array(this.$refs.tree.getCurrentNode())
        }
      }

      this.visible = false
      this.$emit('confirm', selectedNodes || [])
    },
  },
  watch: {
    propVisible(newValue, oldValue) {
      this.visible = newValue
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  created() {
    // this.fetchTreeData()
  },
}
</script>

<style scoped>
</style>
